import $ from "jquery";

export default function net() {
  var net = {
    callback: ('jsonp_' + Math.random()).replace(".", "")
  };

  // 获取项目路径
  var getRootPath = function () {
    return "//api.mp.tianshunet.com/kongtongapp/";
  }

  // 传递参数合并
  var _getData = function (data) {

    const appkey = "1476783185000";
    const versionCode = "1";
    const type = "3";

    if (data == null) {
      data = {};
    }
    var timestamp = Date.parse(new Date());
    data.appkey = appkey;
    data.versionCode = versionCode;
    data.randomCode = timestamp;
    data.type = type;
    //      data.token = rootScope.getToken(); // token 参数
    data.callbackfun = net.callback;
    return data;
  }

  // ajax请求合并
  var _getCommonOpt = function (host, url, data, success, error) {
    var data = _getData(data);
    return {
      url: host + url,
      data: data,
      success: success,
      error: error
    }
  }

  var _sendRequst = function (opt) {

    var obj = {
      url: opt.url,
      type: opt.type,
      data: opt.data,
      dataType: opt.dataType,
      contentType: opt.contentType,
      timeout: opt.timeout || 50000,
      beforeSend: function (xhr) { },
      success: function (json) {
        opt.success && opt.success(json);
      },
      error: function (err) {
        opt.error(err);
      }
    }
    return $.ajax(obj);
  }

  net.cors = function (url, data, success, error) {

  }
  net.get = function (url, data, success, error) {
    var opt;
    opt = this._getCommonOpt(host, url, data, callback, error);
    opt.type = 'get';
    opt.dataType = 'json';
    opt.contentType = 'application/json';
    return this._sendRequst(opt);
  }
  net.post = function (url, data, success, error) {
    var opt;
    opt = this._getCommonOpt(host, url, data, callback, error);
    opt.type = 'post';
    opt.dataType = 'json';
    opt.contentType = 'application/json';
    return this._sendRequst(opt);
  }
  net.jsonp = function (url, data, success, error) {
    var opt;
    var host = getRootPath();
    var oHead = document.getElementsByTagName('head')[0];
    var ele = document.createElement('script');
    ele.type = "text/javascript";
    oHead.appendChild(ele);
    opt = _getCommonOpt(host, url, data, success, error);
    opt.type = 'GET';
    opt.dataType = 'JSONP';
    opt.contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
    _sendRequst(opt);
    ele.onerror = function () {
      error && error("请求失败");
    };
    window[net.callback] = function (json) {
      oHead.removeChild(ele);
      delete window[net.callback];
      success && success(json);
    };
  }

  return net;
}

